package com.atguigu.gmall.rabbit.service;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.rabbit.model.GmallCorrelationData;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 所有业务模块需要发送消息工具类
 *
 * @author: atguigu
 * @create: 2023-09-16 15:27
 */
@Component
public class RabbitService {


    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    /***
     * 发送普通消息方法
     * @param exchange
     * @param routingKey
     * @param msg
     */
    public void sendMessage(String exchange, String routingKey, Object msg) {
        //1.发送消息同时设置相关数据
        GmallCorrelationData gmallCorrelationData = new GmallCorrelationData();
        String id = UUID.randomUUID().toString().replaceAll("-", "");
        gmallCorrelationData.setId(id);
        gmallCorrelationData.setExchange(exchange);
        gmallCorrelationData.setRoutingKey(routingKey);
        gmallCorrelationData.setMessage(msg);

        //2.将相关数据存入Redis，设置5分钟有效期
        String key = "mq:" + id;
        String correlationDataStr = JSON.toJSONString(gmallCorrelationData);
        redisTemplate.opsForValue().set(key, correlationDataStr, 5, TimeUnit.MINUTES);

        //3.执行发送消息-设置相关数据
        rabbitTemplate.convertAndSend(exchange, routingKey, msg, gmallCorrelationData);

    }


    /***
     * 发送延迟消息方法
     * @param exchange
     * @param routingKey
     * @param msg
     * @param dealyTime 延迟时间，单位设置为：秒
     */
    public void sendDelayMessage(String exchange, String routingKey, Object msg, Integer dealyTime) {
        //1.发送消息同时设置相关数据
        GmallCorrelationData gmallCorrelationData = new GmallCorrelationData();
        String id = UUID.randomUUID().toString().replaceAll("-", "");
        gmallCorrelationData.setId(id);
        gmallCorrelationData.setExchange(exchange);
        gmallCorrelationData.setRoutingKey(routingKey);
        gmallCorrelationData.setMessage(msg);
        gmallCorrelationData.setDelay(true);
        gmallCorrelationData.setDelayTime(dealyTime);

        //2.将相关数据存入Redis，设置5分钟有效期
        String key = "mq:" + id;
        String correlationDataStr = JSON.toJSONString(gmallCorrelationData);
        redisTemplate.opsForValue().set(key, correlationDataStr, 5, TimeUnit.MINUTES);

        //3.执行发送消息-设置相关数据
        rabbitTemplate.convertAndSend(exchange, routingKey, msg, (message -> {
            //设置消息过期时间
            message.getMessageProperties().setDelay(dealyTime * 1000);
            return message;
        }), gmallCorrelationData);

    }
}
